import time, os, logging, json
from main.xiaozhi import XiaoZhi
from main.asr_sherpa import ASR_Sherpa
from tools.baby_cry.make_prediction import StreamPrediction
from main.llm_poem import LLM_Ollama
from main.koko_tts import KkTTS

import main.asr
import main.vad

# Set up logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
                    datefmt='%Y-%m-%d %I:%M:%S %p',
                    filename='./logger/xiaozhi.log',
                    filemode='w',
                    level=logging.INFO)
        
def xiaozhi_run():
    """主函数"""
    # 创建语音识别系统实例
    xiaozhi = XiaoZhi(
        threshold=0.5,        # VAD阈值
        silence_limit=1.0,    # 静音1秒表示说话结束
        record_min_length=0.5,  # 最短录音时间0.5秒
        record_timeout=10.0,  # 单次录音最长10秒
        sample_rate=16000,    # 采样率16kHz
        chunk_size=480        # 每次读取30ms的音频
    )
    
    try:
        # 开始录音和识别
        xiaozhi.start_recording()
        
        # 持续运行一段时间
        print("系统运行中...(按Ctrl+C退出)")
        # while True:
        #     time.sleep(1)
            
    except KeyboardInterrupt:
        print("程序退出中...")
    finally:
        # 清理资源
        xiaozhi.cleanup()
        print("程序已退出")

# 哭声检测
def cry_run():
    pre = StreamPrediction()
    pre.start_segment()

# 诗词内容生成图片pt
def llm_run():
    llm = LLM_Ollama(model="gemma3:4b")
    llm.test_parse_learn_poem()
    # llm.test_gen_poem_pt()
    # llm.test_json()

def tts_run():
    p = "Kokoro is an open-weight TTS model with 82 million parameters. Despite its lightweight architecture, it delivers comparable quality to larger models while being significantly faster and more cost-efficient. With Apache-licensed weights, Kokoro can be deployed anywhere from production environments to personal projects."
    p1 = "Kokoro 是一系列体积虽小但功能强大的 TTS 模型。该模型是经过短期训练的结果，从专业数据集中添加了100名中文使用者。中文数据由专业数据集公司「龙猫数据」免费且无偿地提供给我们。感谢你们让这个模型成为可能。另外，一些众包合成英语数据也进入了训练组合：1小时的 Maple，美国女性。1小时的 Sol，另一位美国女性。和1小时的 Vale，一位年长的英国女性。由于该模型删除了许多声音，因此它并不是对其前身的严格升级，但它提前发布以收集有关新声音和标记化的反馈。除了中文数据集和3小时的英语之外，其余数据都留在本次训练中。目标是推动模型系列的发展，并最终恢复一些被遗留的声音。美国版权局目前的指导表明，合成数据通常不符合版权保护的资格。由于这些合成数据是众包的，因此模型训练师不受任何服务条款的约束。该 Apache 许可模式也符合 OpenAI 所宣称的广泛传播 AI 优势的使命。如果您愿意帮助进一步完成这一使命，请考虑为此贡献许可的音频数据。"           
    p2 = """
    Youth– A Poem by Samuel Ullman
    Youth is not a time of life; it is a state of mind; it is not a matter of rosy cheeks, red lips and supple knees; it is a matter of the will, a quality of the imagination, a vigor of the emotions; it is the freshness of the deep springs of life.
    Youth means a temperamental predominance of courage over timidity, of the appetite for adventure over the love of ease. This often exists in a man of 60 more than a boy of 20. Nobody grows old merely by a number of years. We grow old by deserting our ideals.
    Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul. Worry, fear, self-distrust bows the heart and turns the spirit back to dust.
    Whether 60 or 16, there is in every human being's heart the lure of wonder, the unfailing childlike appetite of what's next and the joy of the game of living. In the center of your heart and my heart there is a wireless station: so long as it receives messages of beauty, hope, cheer, courage and power from men and from the Infinite, so long are you young.
    When the aerials are down, and your spirit is covered with snows of cynicism and the ice of pessimism, then you are grown old, even at 20, but as long as your aerials are up, to catch waves of optimism, there is hope you may die young at 80.
    """
    tts = KkTTS(lang_code=KkTTS.has_english_char(text=p2))
    sentences = tts.split_text(text=p2)
    # for line in sentences:
    #     print("====")
    #     print(f"{line}\n")
    tts.start_text_to_audio(sentences = sentences, output="Youth_en")

def tts_run_poem():
    tts = KkTTS(lang_code="z")
    with open("./audios/poem_pinyin.json", "r") as f:
        start = False
        for grade in json.load(f):
            for poem in grade['poems']: 
                if not start:
                    start = (poem["id"] == "70291")
                if poem.get('pinyin') != None and start:
                    id = poem["id"]
                    name = poem["name"]
                    content = poem["content"]
                    sentences = tts.split_text(text=content)
                    tts.start_text_to_audio(sentences = sentences, output=f"../poem_audios/p_{id}_{name}")

if __name__ == "__main__":
     xiaozhi_run()
    #  tts_run()
    # tts_run_poem()
    # llm_run()
    #  cry_run()
  

